<?php

defined( 'IN_DICE' ) or die( 'Access Error!' );

class ModelOnline extends base {
  
  function __construct() {
    parent::__construct();
  }
  
  /**
   * 根据用户ID来获得用户的在线信息
   * 注意从cache中取数据的则没有oltime与pfid这两个字段
   * @param int $uid 用户ID
   * @param bool $cache 是否取缓存
   * @return array
   */
  public function get( $uid, $cache = false ) {
    if( !$uid = uint( $uid ) ) {
      return array();
    }
    $sql = "SELECT * FROM $this->online WHERE uid='$uid' LIMIT 1";
    $aOnline = model::db()->get_one( $sql );
    return $aOnline;
  }

  /**
   * 插入一条在线记录
   * 
   * @param int $uid 用户ID
   * @param int $pfid 平台ID
   * @return array
   */
  public function insert( $uid, $pfid ) {
    if( !$uid = uint( $uid ) ) {
      return array();
    }
    
    $aOnline = array();
    $pfid = uint( $pfid );
    $olkey = func::getrandstr( 32 );
    $time = time();
    $sql = "INSERT INTO $this->online SET uid='$uid',olkey='$olkey',oltime='$time'
            ON DUPLICATE KEY UPDATE oltime='$time'";
    model::db()->exe( $sql );
    $flag = model::db()->update_rows();
    if( $flag ) {
      $aOnline = array(
        'uid' => $uid,
        'olkey' => $olkey,
        'tid' => 0,
        'oltime' => $time,
        'pfid' => $pfid,
        'olstatus' => 0,
      );
    }
    
    return $aOnline;
  }
  
  /**
   * 根据olkey来获得用户在线信息
   *
   * @param string $olkey
   * @return array
   */
  public function getByolkey( $olkey ) {
    $olkey = model::db()->escape( $olkey );
    $sql = "SELECT * FROM $this->online WHERE olkey='$olkey' LIMIT 1";
    $aOnline = model::db()->get_one( $sql );
    
    return $aOnline;
  }
  
  /**
   * 验证一个用户的在线olkey并刷新用户的在线时间, 成功true,失败false
   *
   * @param int $uid
   * @param string $olkey
   * @param int $type 0不限房间 1不能在房间内
   * @return bool
   */
  public function auth( $uid, $olkey, $type = 0 ) {
    $uid = uint( $uid );
    $olkey = model::db()->escape( $olkey );
    $where = $type == 1 ? ' AND tid=0 AND olstatus=0 ' : '';
    $oltime = time();
    $sql = "UPDATE $this->online SET oltime='$oltime'
            WHERE uid='$uid' AND olkey='$olkey' $where LIMIT 1";
    $flag = model::db()->exe( $sql );
    return ( $flag > 0 ) ? true : false;
  }
  
  /**
   * 防刷新限制.每天一次的记录,如每天邀请一次,每天赠送一次等 
   * @param int $uid
   * @param int $ltype 类型 0:flash请求重复验证 
   * @param string $lvalue 限制的值.
   * @param int $delaytime 限制间隔时间
   * @return Boolean
   */
  public function limit( $uid, $ltype, $lvalue, $delaytime = 0 ) {
    if( !($uid = uint( $uid)) || ! strlen( $lvalue ) ) {
      return false;
    }
    $flag = true;
    return $flag;
  }
  
}
